
import { _decorator, Component, Node, AudioClip, AudioSource, assert, warn } from 'cc';
import { Debug } from '../../utils/Debug';
import { settingUtil } from './settingUtil';
const { ccclass, property } = _decorator;

@ccclass('audioManager')
export class audioManager {


    private static _instance: audioManager;
    static get instance() {
        if (this._instance) {
            return this._instance;
        }

        this._instance = new audioManager();
        return this._instance;
    }

    public static playCoin() {
        this.playAudio("coin")
    }

    /**
     * 存储在本地声音有关的设置key（字段字符串）
     * IS_MUTE 是否所有都静音{boolean}
     * IS_MUTE_MUSIC 是否背景音乐静音{boolean}
     * IS_MUTE_SOUND 是否音效静音{boolean}
     * VOLUME_MUSIC 背景音乐音量大小{number}
     * VOLUME_SOUND 音效音量大小{number}
    */
    private IS_MUTE: string = "isMute"
    private IS_MUTE_MUSIC: string = "isMuteMusic"
    private IS_MUTE_SOUND: string = "isMuteSound"
    private VOLUME_MUSIC: string = "volumeMusic"
    private VOLUME_SOUND: string = "volumeSound"
    private _volumeMusic: number = 1
    private _volumeSound: number = 1
    private _isMuteMusic: boolean = false
    private _isMuteSound: boolean = false
    private _isMute: boolean = false

    private gameCoinTime: number = 0;

    public onEnable() {

    }

    private static audioSources: Array<AudioSource> = [];
    private static soundVolume: number = 1;
    // init AudioManager in GameRoot.
    public init(audioSources: Array<AudioSource>) {
        audioManager.audioSources = audioSources;
    }

    private static getSleepAudioSource() {
        for (let i = 0; i < this.audioSources.length; i++) {
            if (!this.audioSources[i].playing) {
                return this.audioSources[i]
            }
        }
    }


    start() {
        this.getSave();
    }



    /**
     * 关闭所有音乐
     */
    public static stopAll() {
        //Laya.SoundManager.stopAll();
        this.audioSources.forEach(item => {
            if (item != this.musicAudioSource) {
                item.stop();
            }
        })
    }

    /**
     * 关闭所有音效
     */
    public static stopSound(name: any) {
        this.audioSources.forEach(item => {
            if (item.clip?.name == name) {
                item.stop();
            }
        })
    }

    /**
     * 关闭所有背景音效
     */
    public static stopMusic() {
        if (this.musicAudioSource) {
            this.musicAudioSource.pause();
            Debug.log('停止播放背景音乐')
        }
    }

    public static pauseMusic() {
        this.musicAudioSource?.pause();
    }
    public static resumeMusic() {
        this.musicAudioSource?.play();
    }

    private static localCache: Array<{
        name: string,
        clip: AudioClip
    }> = []
    public static addAudio(audioClip: AudioClip) {
        Debug.log('addAudio', audioClip.name)
        let has = false;
        this.localCache.forEach(item => {
            if (item.name == audioClip.name && item.clip == audioClip) {
                return;
            }
        })
        this.localCache[this.localCache.length] = {
            clip: audioClip,
            name: audioClip.name
        }
    }

    public static getClip(name: string) {
        for (let i = 0; i < this.localCache.length; i++) {
            let item = this.localCache[i]
            if (item.name == name) {
                return item;
            }
        }
    }

    public static playAudio(name: string, loops: boolean = false) {
        let item = this.getClip(name);
        if (item) {
            this.playSound(item.clip, loops)
        }
    }

    public static stopAudio(name: string) {
        this.stopSound(name)
    }


    /**
     * 关闭单个音效
     * @param 音乐地址
    
    ic stopSound(url: string) {
    //Laya.SoundManager.stopSound(url);
    }

   
    /**
     * 播放音效
     * @param {String} name 音效名称可通过constants.AUDIO_SOUND 获取
     */
    public static playSound(clip: AudioClip, loop: boolean = false,) {
        if (audioManager.instance.isMuteSound) return;

        const audioSource = this.getSleepAudioSource()
        assert(audioSource, 'AudioManager not inited!');

        //音效一般是多个的，不会只有一个
        // let path = 'gamePackage/audio/sound/';
        // if (name !== 'click') {
        //     path = 'gamePackage/' + path; //微信特殊处理，除一开场的音乐，其余的放在子包里头
        // }
        if (audioSource) {
            audioSource.loop = loop
            audioSource.playOneShot(clip, this.soundVolume / audioSource.volume);
        }
        else {
            Debug.log('音频播放资源不足')
        }
    }



    private static musicAudioSource: AudioSource = null!;
    public static playMusic(name: string, loop: boolean = true, volumeMusic: number = 1) {
        if (!this.musicAudioSource) {
            this.musicAudioSource = this.getSleepAudioSource()!;
        }
        if (this.musicAudioSource) {
            this.musicAudioSource.loop = loop;
            let item = this.getClip(name)
            if (item) {
                this.musicAudioSource.clip = item.clip;
                this.musicAudioSource.volume = volumeMusic;
                this.musicAudioSource.play();
            }
        }
        Debug.log('播放背景音乐')
    }


    /**
     * 设置获取背景声音大小
     */
    get volumeMusic() {
        return this._volumeMusic;
    }
    set volumeMusic(value: number) {
        this._volumeMusic = value;
        //Laya.SoundManager.setMusicVolume(value);
        this.save();
    }

    /**
     * 设置获取音效声音大小
     */

    get volumeSound() {
        return this._volumeSound;
    }
    set volumeSound(value) {
        this._volumeSound = value;
        //Laya.SoundManager.setSoundVolume(value);
        this.save();
    }

    /**
     * 设置获取是否静音背景音乐
    */
    get isMuteMusic() {
        return this._isMuteMusic;
    }
    set isMuteMusic(value) {
        this._isMuteMusic = value;
        if (value) {
            audioManager.pauseMusic();
        }
        else {
            audioManager.resumeMusic();
        }
        this.save();
    }

    /**
     * 设置获取是否静音音效音乐
    */
    get isMuteSound() {
        return this._isMuteSound;
    }
    set isMuteSound(value) {
        this._isMuteSound = value;
        //Laya.SoundManager.soundMuted = value;
        this.save();
    }

    /**
     * 设置获取是否所有静音
    */
    get isMute() {
        return this._isMute;
    }
    set isMute(value) {
        this._isMute = value;
        this.save();
    }

    /**
     * 保存数据到本地
    */
    save() {
        settingUtil.setBool(this.IS_MUTE, this.isMute);
        settingUtil.setBool(this.IS_MUTE_MUSIC, this.isMuteMusic);
        settingUtil.setBool(this.IS_MUTE_SOUND, this.isMuteSound);
    }
    getSave() {
        this.isMute = settingUtil.getBool(this.IS_MUTE, false);
        this.isMuteMusic = settingUtil.getBool(this.IS_MUTE_MUSIC, true);
        this.isMuteSound = settingUtil.getBool(this.IS_MUTE_SOUND, true);
    }
}

/**
 * [1] Class member could be defined like this.
 * [2] Use `property` decorator if your want the member to be serializable.
 * [3] Your initialization goes here.
 * [4] Your update function goes here.
 *
 * Learn more about scripting: https://docs.cocos.com/creator/3.0/manual/en/scripting/
 * Learn more about CCClass: https://docs.cocos.com/creator/3.0/manual/en/scripting/ccclass.html
 * Learn more about life-cycle callbacks: https://docs.cocos.com/creator/3.0/manual/en/scripting/life-cycle-callbacks.html
 */
